package com.sws.orderMS.command.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sws.orderMS.OrderMSApplication;
import com.sws.orderMS.OrderMSDao;
import com.sws.orderMS.command.SystemCommand;
import com.sws.orderMS.tool.Tool;

public class SignupCommand extends SystemCommand {

	@Override
	public void execute() {
		OrderMSDao dao = new OrderMSDao();
		
		String username = Tool.askUserInputNotNull("请输入用户名: ");
		while (dao.isUsernameExists(username)) {
			Tool.printMsg("用户名已存在!");
			username = Tool.askUserInputNotNull("请输入用户名: ");
		}
		
		String password = Tool.askUserInputNotNull("请输入密码: ");
		while (!validatePassword(password)) {
			password = Tool.askUserInputNotNull("请输入密码: ");
		}
		
		String name = Tool.askUserInputNotNull("请输入你的名字: ");
		String phone = Tool.askUserInputNotNull("请输入你的电话号码: ");
		String address = Tool.askUserInputNotNull("请输入你的联系地址: ");
		dao.signup(username, password, name, phone, address);

	}
	
	private boolean validatePassword(String password) {
		// length < 6
		if (password.trim().length() < 6) {
			Tool.printMsg("password need at least 6 characters!");
			return false;
		}
		
		// all letters
		Pattern numPattern = Pattern.compile("[0-9]");
		Matcher numMatcher = numPattern.matcher(password.trim());
		if (!numMatcher.find()) {
			Tool.printMsg("password can't be all letters!");
			return  false;
		}
		
		// all numbers
		Pattern letterPattern = Pattern.compile("[A-Za-z]");
		Matcher letterMatcher = letterPattern.matcher(password.trim());
		if (!letterMatcher.find()) {
			Tool.printMsg("password can't be all numbers!");
			return  false;
		}
		
		return true;
	}

}
